package com.joker.aigc.chat.service.event.listener;


import com.joker.aigc.domain.entity.User;
import com.joker.aigc.domain.enums.WebSocketChatActiveStatusEnum;
import com.joker.aigc.chat.service.IpService;
import com.joker.aigc.chat.service.PushService;
import com.joker.aigc.service.UserService;
import com.joker.aigc.chat.service.adapter.WebSocketAdapter;
import com.joker.aigc.chat.service.event.UserOnlineEvent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * 用户上线监听器
 *
 * @author zhongzb create on 2022/08/26
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class UserOnlineListener {


    private final UserService userService;
    private final IpService ipService;
    private final PushService pushService;


    @Async
    @EventListener(classes = UserOnlineEvent.class)
    public void saveRedisAndPush(UserOnlineEvent event) {
        User user = event.getUser();
        log.info("login step 2-3 成功登录--发送rabbitmq消息，该用户上线");
//        User user = event.getUser();
        //推送给所有在线用户，该用户登录成功
        pushService.sendWebSocketAll(WebSocketAdapter.buildOnlineNotifyResp(event.getUser()), user.getId());
        // redis缓存全局在线人数
        userService.addOnline(user.getId());

    }

    @Async
    @EventListener(classes = UserOnlineEvent.class)
    public void saveDB(UserOnlineEvent event) {
        log.info("login step 2-4 成功登录--修改用户最后登录信息。刷新ip和最后登录时间");
        User user = event.getUser();
        User update = new User();
        update.setId(user.getId());
        update.setLastOptTime(user.getLastOptTime());
        update.setIpInfo(user.getIpInfo());
        update.setActiveStatus(WebSocketChatActiveStatusEnum.ONLINE.getStatus());
        userService.updateById(update);
        //更新用户ip详情
        ipService.refreshIpDetailAsync(user.getId());
    }

}
